import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    todoList: JSON.parse(localStorage.getItem('todoList') || '[]'),
    type: 'all'
  },
  getters: {
    // renderTodoList这个计算属性是页面渲染时需要用到的数据，他是根据总的数据数据和任务类型 计算得到的
    renderTodoList (state) {
      if (state.type === 'all') {
        return state.todoList
      } else if (state.type === 'active') {
        return state.todoList.filter((item) => !item.isCompleted)
      } else {
        return state.todoList.filter((item) => item.isCompleted)
      }
    }
  },
  mutations: {
    // 新增任务数
    addTodo (state, payload) {
      const idArr = state.todoList.map((item) => item.id)
      let max = Math.max.apply(null, idArr)
      if (max < 0) max = 0
      const tempObj = {
        id: max + 1,
        title: payload,
        isCompleted: false
      }
      state.todoList.unshift(tempObj)
      // 添加数据除了往vuex的state中添加，还需要往本地存储保存一份
      localStorage.setItem('todoList', JSON.stringify(state.todoList))
    },
    updateStatus (state, id) {
      // 找到索引
      const index = state.todoList.findIndex((item) => item.id === id)
      state.todoList[index].isCompleted = !state.todoList[index].isCompleted
      localStorage.setItem('todoList', JSON.stringify(state.todoList))
    },
    del (state, id) {
      const index = state.todoList.findIndex((item) => item.id === id)
      state.todoList.splice(index, 1)
      localStorage.setItem('todoList', JSON.stringify(state.todoList))
    },
    toggleType (state, type) {
      state.type = type
    }
  },
  actions: {
  },
  modules: {
  }
})
